
import { takeEvery, put } from 'redux-saga/effects'
import { addProductToCart, addProductToLocalCart, changeProductNumber, changeServiceProductNumber, deleteProductFromCart, deleteProductFromLocalCart, loadCarts, saveCarts } from '../actions/cart.actions'
import axios from 'axios'

// 将商品保存到服务器端购物车数据列表 拿到最新的数据列表
function* handleAddProductCart(action) {
  const { data } = yield axios.post('http://localhost:3005/cart/add', {gid: action.payload})
  yield put(addProductToLocalCart(data))
} 

// 从服务器端获取购物车商品数据列表
function* handleLoadCarts() {
  const { data } = yield axios.get('http://localhost:3005/cart')
  yield put(saveCarts(data))
}
// 从服务器端删除商品
function* handleDeleteProductFromCart(action) {
  const { data } = yield axios.delete('http://localhost:3005/cart/delete', {params: {cid: action.payload}})
  yield put(deleteProductFromLocalCart(data.index))
}
// 向服务器端发送请求 更改商品数量
function* handleChangeServiceProductNumber(action) {
  const { data } = yield axios.put('http://localhost:3005/cart', {cid: action.payload.cid, count: action.payload.count})
  yield put(changeProductNumber(data))
}

// 触发参数1的action，执行参数2的函数操作
export default function* cartSaga() {
  yield takeEvery(addProductToCart, handleAddProductCart)
  yield takeEvery(loadCarts, handleLoadCarts)
  yield takeEvery(deleteProductFromCart, handleDeleteProductFromCart)
  yield takeEvery(changeServiceProductNumber, handleChangeServiceProductNumber)
}